package com.leyou.seckill.mq;

import com.leyou.common.constants.MQConstants;
import com.leyou.seckill.mapper.SeckillMapper;
import com.leyou.seckill.pojo.SeckillItem;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.Map;

/**
 * 监听mq从而异步添加订单
 *
 * @author RudolfHugh
 * @since 2020/5/29 16:31
 */
@Component
public class SeckillListener {

  @Autowired private SeckillMapper seckillMapper;

  @RabbitListener(
      bindings =
          @QueueBinding(
              value =
                  @Queue(
                      value = MQConstants.Queue.SECKILL_QUEUE,
                      durable = "true"), // 定义队列的名称和是否持久化
              exchange =
                  @Exchange(
                      value = MQConstants.Exchange.SECKILL_EXCHANGE_NAME,
                      type = ExchangeTypes.TOPIC,
                      // springboot会自动创建交换机：如果为true：创建交换机失败之后继续创建其他属性
                      ignoreDeclarationExceptions = "true"),
              key = MQConstants.RoutingKey.SECKILL_KEY))
  public void createOrder(Map map) {
    System.out.println("=============>" + map.get("userId") + " 用户成功秒杀到了->" + map.get("skuId"));
    SeckillItem seckillItem = new SeckillItem();
    seckillItem.setStock((Long) map.get("stock"));
    Example example = new Example(SeckillItem.class);
    example.createCriteria().andEqualTo("skuId", map.get("skuId"));
    int count = seckillMapper.updateByExampleSelective(seckillItem, example);
  }
}
